package dongze.com.ckdj.fragment;

import android.app.Activity;
import android.support.v7.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dongze.com.ckdj.R;
import dongze.com.ckdj.activity.CheckInOperationItemSelectionActivity;
import dongze.com.ckdj.activity.SelectCheckPointActivity;
import dongze.com.ckdj.adapter.ListItem;
import dongze.com.ckdj.adapter.TypedListItem;
import dongze.com.ckdj.adapter.VehicleInformationAdapter;
import dongze.com.ckdj.dagger.component.VehicleComponent;
import dongze.com.ckdj.data.IRecordRequestBuilder;
import dongze.com.ckdj.data.entity.request.Record;
import dongze.com.ckdj.data.entity.request.RecordRequestBody;
import dongze.com.ckdj.data.entity.response.InspectionSection;
import dongze.com.ckdj.data.entity.response.InspectionSectionResponse;
import dongze.com.ckdj.data.entity.response.User;
import dongze.com.ckdj.data.entity.response.VehicleInformationDetail;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;

/**
 * Created by fanqwz on 2017/7/20.
 */

public class VehicleInformationFragment extends ProcessableFragment implements AdapterView.OnItemClickListener {
    private static final int REQUEST_CODE = 2000;
    @BindView(R.id.save_record)
    Button saveBtn;
    @BindView(R.id.infomation_list)
    ListView listView;
    VehicleInformationAdapter adapter = new VehicleInformationAdapter();
    ListItem[] listItems;

    @Inject
    VehicleInformationDetail vehicleInformationDetail;
    @Inject
    InspectionSectionResponse mInspectionSection;
    @Inject
    User user;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getComponent(VehicleComponent.class) != null) {
            getComponent(VehicleComponent.class).inject(this);
        } else {
            getFragmentManager().beginTransaction().remove(this).commit();
        }

        if (vehicleInformationDetail != null
                && vehicleInformationDetail.getVin_info() != null
                && vehicleInformationDetail.getVin_info().size() != 0) {
            listItems = new ListItem[vehicleInformationDetail.getVin_info().size()];

            for (int i = 0; i < listItems.length; i++) {
                listItems[i] = new ListItem();
                listItems[i].setKey(vehicleInformationDetail.getVin_info().get(i).getKey());
                listItems[i].setValue(vehicleInformationDetail.getVin_info().get(i).getValue());
            }

            doProcessing();
            buildInfomationModel();
        }
    }

    @Nullable
    @Override
    public View createContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_vehicle_information, container, false);
        ButterKnife.bind(this, root);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
        buildInfomationModel();

        if (listItems == null || listItems.length == 0)
            saveBtn.setEnabled(false);

        return root;
    }

    @OnClick(R.id.save_record)
    public void save(View view) {
        if (listItems == null || listItems.length == 0)
            return;

        doProcessing();

        final RecordRequestBody recordRequestBody = new RecordRequestBody();
        Record record = new Record();
        record.setType("2"/*车身*/);
        record.setBrand_code(vehicleInformationDetail.getBrand_code());
        record.setBrand_name(vehicleInformationDetail.getBrand_name());
        record.setVin(vehicleInformationDetail.getVin());
        record.setUser_no(user.getUser_no());
        record.setUser_name(user.getUser_name());
        record.setNode_code(mInspectionSection.getNode_code());
        record.setNode_name(mInspectionSection.getNode_name());
        recordRequestBody.setRecord(record);
        adapter.build(recordRequestBody)
                .subscribe(new Consumer<RecordRequestBody>() {
                    @Override
                    public void accept(RecordRequestBody recordRequestBody) throws Exception {
                        mapUtil.addRecord(recordRequestBody, new DisposableObserver<String>() {

                            @Override
                            protected void onStart() {
                                super.onStart();
                            }

                            @Override
                            public void onNext(String value) {
                                finishProcessing();
                                Toast.makeText(getContext(), value, Toast.LENGTH_LONG).show();
                            }

                            @Override
                            public void onError(Throwable e) {
                                e.printStackTrace();
                                finishProcessing();
                                new AlertDialog.Builder(getContext())
                                        .setTitle("错误")
                                        .setMessage("保存记录失败：" + e.getMessage())
                                        .create()
                                        .show();
                            }

                            @Override
                            public void onComplete() {
                                adapter.setListItems(null);
                                adapter.notifyDataSetChanged();
                                saveBtn.setEnabled(false);
                            }
                        });
                    }
                });
    }

    private void buildInfomationModel() {
        if (listView != null && listItems != null) {
            adapter.setListItems(listItems);
            adapter.notifyDataSetChanged();
            finishProcessing();
        }
    }

    @OnClick(R.id.mass_loss_btn)
    void onMassLossBtnClick(View view) {
        SelectCheckPointActivity.actionStart(getActivity(), vehicleInformationDetail.getVoyage(), vehicleInformationDetail.getType(), "", "");
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(view.getContext().getApplicationContext(), CheckInOperationItemSelectionActivity.class);
        intent.putExtra("key", listItems[position].getKey());
        intent.putExtra("value", listItems[position].getValue());
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK && data != null) {
                String key = data.getStringExtra("key");
                String value = data.getStringExtra("value");

                if (!TextUtils.isEmpty(key)) {
                    for (ListItem i :
                            listItems) {
                        if (TextUtils.equals(i.getKey(), key)) {
                            i.setValue(value);
                            adapter.notifyDataSetChanged();
                            break;
                        }
                    }
                }
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}
